package com.mtw.bbs.bbsUser.utils;

import com.mtw.bbs.userAdmin.pojo.vo.MenuVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class TreeUtil {


    public static List<MenuVo> list2Tree(List<MenuVo> all){

        Map<String, List<MenuVo>> tempMap = new LinkedHashMap<>(all.size());
        //最顶层的根节点
        List<MenuVo> rootList = new ArrayList<>();

        for (MenuVo node : all) {

            // 设置子列表
            List<MenuVo> childList;
            if (tempMap.containsKey(node.getId())){
                childList = tempMap.get(node.getId());
            }else {
                childList = new ArrayList<>(8);
                tempMap.put(node.getId(),childList);
            }
            node.setChildMenu(childList);

            if (StringUtils.isBlank(node.getParentId())){
                rootList.add(node);
            }else {
                // 将当前节点放入子节点列表
                List<MenuVo> sonList = tempMap.computeIfAbsent(node.getParentId(), k -> new ArrayList<>(8));
                sonList.add(node);
            }
        }
        return dataSort(rootList);
    }


    /**
     * 排序
     */
    private static List<MenuVo> dataSort(List<MenuVo> data){
        if (CollectionUtils.isEmpty(data)){
            return data;
        }
        AtomicInteger index = new AtomicInteger(1);
        return data.stream().peek(x->x.setChildMenu(dataSort(x.getChildMenu())))
                .sorted(Comparator.comparing(d -> d.getSort() == null ? 100 : d.getSort()))
                .peek(x->x.setDataIndex(index.getAndIncrement())).toList();
    }

}
